import {Button, Col, DatePicker, Form, Input, InputNumber, message, Radio, Select, Tooltip} from "antd";
import React, {Component, useState} from "react";
import Dictionary from "../../services/dictionary";
import moment from "moment/moment";
import {DownloadOutlined, FileAddOutlined, SearchOutlined} from "@ant-design/icons";
import Utils from "../../utils";
import {ygxxApi} from "../../services/basic";

const {RangePicker} = DatePicker;

const defDateFormat = "YYYY-MM-DD";

// 通用select
class MySelect extends Component {
    constructor(props) {
        super(props);
        this.state = {
            label: props.label,
            placeholder: props.placeholder || "输入关键字查找",
            // 全部options
            allOptions: [],
            // 匹配options
            showOptions: [],
            // 字段名
            keyword: props.keyword,
            // 选项对应的key
            // optionKey: "",
            // value
            value: null,
            // col:span
            span: props.colSpan || 4,
            // rules
            rules: props.rules || [],
            disabled: false
        }
    }

    // 查询Dic
    getDic() {
        return new Promise(resolve => {
            resolve([]);
        })
    }

    // 设置全部选项
    getOptions = () => {
        this.getDic().then(list => {
            this.setState({
                allOptions: list
            })
            this.onSearch();
        })
    }

    // 匹配search
    onSearch = (val = "") => {
        const list = this.state.allOptions.filter(item => {
            return item.label.includes(val.trim());
        })
        this.setState({
            showOptions: list || [],
        })
    }

    onFocus = () => {
        // focus
    }

    // change
    onChange = (_, e) => {
        const {onFormChange} = this.props;
        if (onFormChange) onFormChange({
            [this.state.keyword]: e ? e.value : null
        }, e)
    }

    render() {
        const {showOptions, rules, disabled} = this.state;
        // label 和 value一致
        const useNameAsValue = this.props.useNameAsValue;
        return (
            <Col span={this.state.span} key={this.state.keyword}>
                <Form.Item label={this.state.label} name={this.state.keyword} rules={rules}>
                    <Select
                        disabled={disabled}
                        allowClear
                        placeholder={this.state.placeholder}
                        filterOption={false}
                        showSearch={true}
                        value={this.state.value}
                        onChange={this.onChange}
                        onSearch={this.onSearch}
                        onFocus={this.onFocus}
                    >
                        {showOptions.map(item => {
                            return (
                                <Select.Option key={item.value} value={useNameAsValue ? item.label : item.value}>
                                    {item.label}
                                </Select.Option>
                            )
                        })}
                    </Select>
                </Form.Item>
            </Col>
        )
    }
}

// 公司名称-Select
class SelectCompanies extends MySelect {
    constructor(props) {
        super(props);
        const {label, keyword} = props;
        this.state.label = label || "公司名称";
        this.state.placeholder = "输入关键字查找";
        this.state.keyword = keyword || "yybm";
        this.getDic = Dictionary.getCompanies;
        this.getOptions();
    }
}

// 跟进状态-Select
class SelectFollowState extends MySelect {
    constructor(props) {
        super(props);
        this.state.label = "跟进状态";
        this.state.placeholder = "请选择跟进状态";
        this.state.keyword = "gjzt";
        // this.state.optionKey = "yymc";
        this.getDic = Dictionary.getFollowState;
        this.getOptions();
    }
}

// 意向项目-Select
class SelectProjects extends MySelect {
    constructor(props) {
        super(props);
        this.state.label = "意向项目";
        this.state.placeholder = "请选择意向项目";
        this.state.keyword = "yxxm";
        this.getDic = Dictionary.getProjects;
        this.getOptions();
    }
}

// 人员列表
class SelectPerson extends MySelect {
    constructor(props) {
        super(props);
        this.state.label = props.label || "创建人";
        this.state.placeholder = props.placeholder || "请选择人员";
        this.state.keyword = props.keyword || "cjrid";
        this.getDic = Dictionary.getPerson;
        this.getOptions();
    }
}

// 微信客服-Select  更名：客服/销售
class SelectPersonWx extends SelectPerson {
    constructor(props) {
        super(props);
        this.state.label = props.label || "客服/销售";
        this.state.keyword = props.keyword || "lxr";
    }
}

// 根据公司和职位获取联系人，公司：表单联动，职位：固定
class SelectCompanyPerson extends MySelect {
    constructor(props) {
        super(props);
        this.state.label = props.label || "联系人";
        this.state.placeholder = props.placeholder || "请选择人员";
        this.state.keyword = props.keyword || "lxr";
        this.yybm = this.props.dataForm.yybm
        this.zw = props.zw || "";
        this.getOptions();
    }

    yybm = null
    // 职位：6微信客服
    zw = ""

    componentDidUpdate(nextProps, prevState) {
        const yybm = this.props.dataForm.yybm
        if (this.yybm !== yybm) {
            this.yybm = yybm
            // this.onChange(null, {value: null})
            this.getOptions()
        }
    }

    getOptions = () => {
        ygxxApi.search({search: "", yybm: this.yybm, zw: this.zw}).then(res => {
            const oldList = res["records"] || [];
            const list = [];
            oldList.forEach(item => {
                list.push({
                    value: item.gh,
                    label: item.xm
                })
            })
            this.setState({
                allOptions: list
            })
            this.onSearch();
        })
    }
}

// 微信客服-Select  真微信客服，前面的包含客服/销售，且需联动表单里的公司查询
class SelectPersonWx2 extends MySelect {
    constructor(props) {
        super(props);
        this.state.label = props.label || "微信客服";
        this.state.placeholder = props.placeholder || "请选择微信客服";
        this.state.keyword = props.keyword || "lxr";
        // this.yybm = this.props.dataForm.yybm
        this.zw = props.zw || "";
        this.getOptions();
    }

    yybm = null
    // 职位：6微信客服
    zw = ""

    getOptions = () => {
        ygxxApi.search({search: "", zw: this.zw}).then(res => {
            const oldList = res["records"] || [];
            const list = [];
            oldList.forEach(item => {
                list.push({
                    value: item.gh,
                    label: item.xm
                })
            })
            this.setState({
                allOptions: list
            })
            this.onSearch();
        })
    }
}

// 人员，联动公司，根据zw查询，默认不传查该公司全部人员
class SelectPersonZw extends SelectCompanyPerson {
    constructor(props) {
        super(props);
        this.state.label = props.label || "联系人";
        this.state.placeholder = props.placeholder || "请选择人员";
        this.state.keyword = props.keyword || "lxr";
        // 职位3: 导购
        this.zw = props.zw;
        this.getOptions();
    }
}

// 抖音客服-Select
class SelectPersonDy extends SelectPerson {
    constructor(props) {
        super(props);
        this.state.label = props.label || "抖音客服";
        this.state.keyword = props.keyword || "dykh";
    }
}

// 创建人-Select(未使用)
class SelectCreator extends SelectPerson {
    constructor(props) {
        super(props);
        this.state.label = props.label || "创建人";
        this.state.keyword = props.keyword || "cjrid";
    }
}

// 联系来源-Select
class SelectChannel extends MySelect {
    constructor(props) {
        super(props);
        this.state.label = props.label || "联系来源";
        this.state.placeholder = props.placeholder || "请选择联系来源";
        this.state.keyword = props.keyword || "lxly";
        this.getDic = Dictionary.getChannel;
        this.getOptions();
    }
}

// 核对与否-Select
class SelectCheck extends MySelect {
    constructor(props) {
        super(props);
        this.state.label = props.label || "核对状态";
        this.state.placeholder = props.placeholder || "请选择核对状态";
        this.state.keyword = props.keyword || "jz";
        this.getDic = Dictionary.getCheckState;
        this.getOptions();
    }

    render() {
        // 传true需要做权限限制
        const {permission} = this.props;
        if (permission) {
            const userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
            return userInfo && [4, "4"].includes(userInfo.zw) ? super.render() : null;
        } else {
            return super.render();
        }
    }

}

// 职务-Select
class SelectPositions extends MySelect {
    constructor(props) {
        super(props);
        this.state.label = props.label || "工作职务";
        this.state.placeholder = props.placeholder || "请选择工作职务";
        this.state.keyword = props.keyword || "zw";
        this.getDic = Dictionary.getPositions;
        this.getOptions();
    }
}

// 账号-Select
class SelectAccount extends MySelect {
    constructor(props) {
        super(props);
        this.state.label = props.label || "账号名称";
        this.state.placeholder = props.placeholder || "请选择账号";
        this.state.keyword = props.keyword || "sfzh";
        this.getDic = Dictionary.getAccounts
        this.getOptions();
    }
}

// “计划”里的账号-Select
class SelectJhAccount extends MySelect {
    constructor(props) {
        super(props);
        this.state.label = props.label || "账号名称";
        this.state.placeholder = props.placeholder || "请选择账号";
        this.state.keyword = props.keyword || "sfzh";
        this.getDic = Dictionary.getJhAccounts
        this.getOptions();
    }
}

// 是否有效-Select
class SelectState extends Component {
    constructor(props) {
        super(props);
        this.state = {
            value: 1,
            keyword: props.keyword || "ztbz"
        }

        const userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
        const isAdmin = userInfo.yhbh === "admin";
        this.isAdmin = isAdmin;

        const {onFormChange} = this.props;
        if (onFormChange) onFormChange({
            [this.state.keyword]: isAdmin ? 3 : 1
        }, {})
    }

    // change
    onChange = (_, e) => {
        const {onFormChange} = this.props;
        if (onFormChange) onFormChange({
            [this.state.keyword]: e ? e.value : null
        }, e)
    }

    render() {
        return this.isAdmin ? (<Col span={4}>
            <Form.Item label="是否有效" name={this.state.keyword} rules={this.props.rules || []}>
                <Select
                    allowClear
                    placeholder="选择有效性"
                    value={this.state.value}
                    onChange={this.onChange}
                >
                    {
                        Object.entries(Dictionary.validity).map(([key, value]) => {
                            return <Select className="Option" key={key} value={key}>{value}</Select>
                        })
                    }
                </Select>
            </Form.Item>
        </Col>) : null;
    }
}

class SelectState2 extends Component {
    constructor(props) {
        super(props);
        this.state = {
            value: props.defaultValue || null,
            keyword: props.keyword || "ztbz",
            colSpan: props.colSpan || 4,
            defaultValue:props.defaultValue || null
        }
        if(props.defaultValue!==null) this.onChange(false, {value: this.state.value})
    }

    // change
    onChange = (_, e) => {
        const {onFormChange} = this.props;
        if (onFormChange) onFormChange({
            [this.state.keyword]: e ? e.value : null
        }, e)
    }

    render() {
        const {keyword, colSpan,defaultValue} = this.state
        return <Col span={colSpan}>
            <Form.Item label="是否有效" name={keyword} rules={this.props.rules || []}>
                <Select
                    defaultValue={defaultValue}
                    allowClear
                    placeholder="选择有效性"
                    value={this.state.value}
                    onChange={this.onChange}
                >
                    <Select.Option value={1}>有效</Select.Option>
                    <Select.Option value={0}>无效</Select.Option>
                </Select>
            </Form.Item>
        </Col>
    }
}

// 职位-Select, 仅销售、微信客服，且传参值不一样
class ZwSelect extends Component {
    constructor(props) {
        super(props);
        this.state = {
            // value: null,
            keyword: props.keyword || "zw"
        }
    }

    // change
    onChange = (_, e) => {
        const {onFormChange} = this.props;
        if (onFormChange) onFormChange({
            [this.state.keyword]: e ? e.value : null
        }, e)
    }

    render() {
        return (<Col span={4}>
            <Form.Item label="职位" name={this.state.keyword} rules={this.props.rules || []}>
                <Select
                    allowClear
                    placeholder="选择职位"
                    value={this.state.value}
                    onChange={this.onChange}
                >
                    <Select className="Option" key={2} value={2}>销售</Select>
                    <Select className="Option" key={6} value={6}>微信客服</Select>
                </Select>
            </Form.Item>
        </Col>);
    }
}

// 计划下拉
class JhSelect extends MySelect {
    constructor(props) {
        super(props)
        this.state.label = props.label || "计划名称";
        this.state.placeholder = props.placeholder || "请选择计划";
        this.state.keyword = props.keyword || "jhid";
        this.state.disabled = false
        this.zhKey = this.props.zhKey || "sfzh"
    }

    // 传进来的dataForm的对应来源账号的key
    zhKey = "sfzh"
    lyzh = null

    componentDidUpdate(nextProps, prevState) {
        const lyzh = this.props.dataForm[this.zhKey]
        if (this.lyzh !== lyzh) {
            this.changeLyzh(lyzh)
        }
    }

    // 更新来源账号时，重新请求
    changeLyzh(val) {
        this.lyzh = val
        this.setState({
            disabled: !val,
            // 清空值没生效
            value: null,
            allOptions: []
        }, () => {
            if (val) {
                this.getOptions()
            }
        })
    }

    // 查询Dic
    getDic() {
        return new Promise(resolve => {
            ygxxApi.getPromotes({lyzh: this.lyzh}).then(res => {
                const list = [];
                res.records.forEach(item => {
                    list.push({
                        label: item.jhmc,
                        value: item.jhid
                    })
                })
                resolve(list);
            }).catch(err => {
                console.error(err)
            })
        })
    }

    onFocus() {
        if (this.state.allOptions.length === 0) {
            message.warning("该账号无可选计划")
        }
    }
}

// 平台
class SelectPlatform extends MySelect {
    constructor(props) {
        super(props);
        this.state.label = props.label || "发布平台";
        this.state.placeholder = props.placeholder || "请选择平台";
        this.state.keyword = props.keyword || "fbpt";
        // this.getDic = Dictionary.getAccounts
        this.getOptions();
    }

    getDic() {
        return new Promise(resolve => {
            const list = [];
            for (let key in Dictionary.platform) {
                list.push({
                    label: Dictionary.platform[key],
                    value: key,
                })
            }
            resolve(list);
        })
    }
}

// 拍摄项目
// class SelectShootProjects extends MySelect {
//     constructor(props) {
//         super({
//             label: "拍摄项目",
//             placeholder: "请选择拍摄项目",
//             keyword: "psxm",
//             ...props
//         });
//         // this.getDic = Dictionary.getAccounts
//         this.getOptions();
//     }
//
//     getDic() {
//         return new Promise(resolve => {
//             const list = Dictionary.shootProjects.map(name => {
//                 return {
//                     label: name,
//                     value: name,
//                 }
//             });
//             resolve(list);
//         })
//     }
// }

// 拍摄状态
class SelectShootStates extends MySelect {
    constructor(props) {
        super(props);
        this.state.label = props.label || "拍摄状态";
        this.state.placeholder = props.placeholder || "请选择状态";
        this.state.keyword = props.keyword || "zt";
        // this.getDic = Dictionary.getAccounts
        this.getOptions();
    }

    getDic() {
        return new Promise(resolve => {
            const list = []
            Dictionary.shootStates.forEach((name, index) => {
                list.push({
                    label: name,
                    value: index
                })
            })
            resolve(list);
        })
    }
}

// 日期选择器
/*class MyDatePicker extends Component {
    constructor(props) {
        super(props);
        this.state = {
            keyword: props.keyword || "jdrq",
            label: props.label || "进店日期",
            colSpan: props.colSpan || 4,
            format: props.format || defDateFormat
        }
        // this.todayVal = moment(new Date()).format(defDateFormat);
    }

    // 禁用超过今天的日期
    disabledDate = (current) => {
        return current && current > this.today;
    }

    componentDidMount() {
    }

    onChange = (value) => {
        const {onFormChange} = this.props;
        onFormChange({
            [this.state.keyword]: moment(value).format(this.state.format),
        })
    }

    render() {
        const {keyword, label, colSpan, format} = this.state;
        return (<Col span={colSpan}>
            <Form.Item label={label} name={keyword} rules={this.props.rules || []}
            >
                <DatePicker key={this.state.keyword}
                            valueFormat={format}
                            format={format}
                    // defaultValue="2025-07-16"
                            style={{width: "100%"}}
                    // disabledDate={this.disabledDate}
                    // onChange={this.onChange}
                ></DatePicker>
            </Form.Item></Col>)
    }
}*/

// 日期范围 基础配置
class DPR extends Component {
    constructor(props) {
        super(props);
        const {showTime} = props;
        const {
            format = showTime ? 'YYYY-MM-DD HH:mm:ss' : defDateFormat,
            label = "日期范围",
            start = "qsrq",
            end = "zzrq",
        } = this.props;
        this.state = {
            label, start, end
        }
        this.format = format;
    }

    // 日期初始化，避免过早触发queryList
    dateInit() {
        // Moment.js 文档：https://momentjs.cn/docs/
        // Day.js 中文网：https://day.nodejs.cn/
        // moment.locale('zh-cn');
        const now = new Date();
        const {showTime} = this.props;

        now.setHours(23);
        now.setMinutes(59);
        now.setSeconds(59);
        this.today = moment(now, this.format);


        const defaultValue = [];
        if (showTime) {
            const zero = new Date()
            zero.setHours(0);
            zero.setMinutes(0);
            zero.setSeconds(0);
            defaultValue.push(moment(zero, this.format))
            defaultValue.push(this.today)
        } else {
            defaultValue.push(this.today)
            defaultValue.push(this.today)
        }

        this.defaultValue = defaultValue
        this.onChange(defaultValue)

        this.props.itemInitCb();
    }

    // 禁用超过今天的日期
    disabledDate = (current) => {
        return current && current > this.today;
    }

    // 会触发2次：startChange、endChange
    onChange = (values) => {
        const {saveDateRange} = this.props;
        const dateObj = {
            start: values ? moment(values[0]).format(this.format) : null,
            end: values ? moment(values[1]).format(this.format) : null
        }

        this.onReadyChange(dateObj);
        saveDateRange && saveDateRange(dateObj);
    }

    onReadyChange(dateObj) {
        const {start, end} = this.state;
        const {onFormChange} = this.props;
        onFormChange({
            [start]: dateObj.start,
            [end]: dateObj.end,
        })
    }

    render() {
        const {colSpan = 8, showTime = false} = this.props;
        const {label} = this.state
        return (
            <Col span={colSpan}>
                <Form.Item label={label}>
                    <RangePicker
                        showTime={showTime}
                        style={{width: "100%"}}
                        defaultValue={this.defaultValue}
                        // locale={zhCN}
                        format={this.format}
                        disabledDate={this.disabledDate}
                        onChange={this.onChange}
                    />
                </Form.Item>
            </Col>
        )
    }
}

// 日期范围
class DatePickerRange extends DPR {
    constructor(props) {
        super(props);
        this.dateInit();
    }
}

// 可选的日期范围
class ChooseDatePickerRange extends DPR {
    constructor(props) {
        super(props);
        this.dateInit();
    }

    onReadyChange(dateObj) {
        const {onFormChange} = this.props;
        onFormChange({
            ddqsrq: dateObj.start,
            ddzzrq: dateObj.end,
            cjqsrq: dateObj.start,
            cjzzrq: dateObj.end,
        })
    }
}

// 可选的日期范围
// 到店日期：ddqsrq~ddzzrq
// 成交日期：cjqsrq~cjzzrq
// 综合日期：两个都传值
/*class ChooseDatePickerRange_backup extends DatePickerRange {
    constructor(props) {
        const defaultType = "ddrq";
        const DateTypeSelect = () => {
            return (<Select
                defaultValue={defaultType}
                onChange={this.dateTypeChange}
                options={[
                    {value: "ddrq", label: "到店日期"},
                    {value: "cjrq", label: "成交日期"},
                    {value: "zhrq", label: "综合日期"},
                ]}/>)
        }
        // DatePickerRange constructor触发的this.onChange不是子类实例的onChange
        super(props);
        this.state.label = <DateTypeSelect/>;
        this.state.start = "ddqsrq";
        this.state.end = "ddzzrq";

        this.startVal = moment(this.today).format(this.format);
        this.endVal = moment(this.today).format(this.format);
        this.onChange = this.onChange.bind(this);
        this.type = defaultType;
    }

    dateTypeChange = (val) => {
        this.type = val;
        this.onRealChange();
    }

    // 日期组件切换触发
    onChange = (values) => {
        this.startVal = values ? moment(values[0]).format(this.format) : null;
        this.endVal = values ? moment(values[1]).format(this.format) : null;
        this.onRealChange();
    }

    // form数据更新
    onRealChange = () => {
        const {onFormChange, saveDateRange} = this.props;
        if (this.type === "ddrq") {
            onFormChange({
                ddqsrq: this.startVal,
                ddzzrq: this.endVal,
                cjqsrq: null,
                cjzzrq: null,
            })
        } else if (this.type === "cjrq") {
            onFormChange({
                ddqsrq: null,
                ddzzrq: null,
                cjqsrq: this.startVal,
                cjzzrq: this.endVal,
            })
        } else {
            onFormChange({
                ddqsrq: this.startVal,
                ddzzrq: this.endVal,
                cjqsrq: this.startVal,
                cjzzrq: this.endVal,
            })
        }
        saveDateRange && saveDateRange({
            start: this.startVal,
            end: this.endVal,
        })
    }
}*/

// 文本输入框-Input
function InputText({onFormChange, colSpan, label, keyword}) {
    const onBlur = (e) => {
        if (onFormChange) onFormChange({
            [keyword]: e ? e.target.value : null
        }, e)
    }

    return (
        <Col span={colSpan || 4}>
            <Form.Item label={label} name={keyword}>
                <Input allowClear placeholder="输入关键字" onBlur={onBlur}></Input>
            </Form.Item>
        </Col>
    )
}

function periodRadio  ({onFormChange, colSpan, label, keyword='sjlx'}) {
    const onchange = (e)=>{
        if (onFormChange) onFormChange({
            [keyword]: e ? e.target.value : null
        }, e)
    }
    return <>
        <Form.Item label='留资时段' name="sjlx">
            <Radio.Group
                onChange={onchange}
                defaultValue={0}
                optionType="button"
                options={[
                    {value: 0, label: "全部"},
                    {value: 1, label: <Tooltip title="17:30之前">白天</Tooltip>},
                    {value: 2, label: <Tooltip title="17:30之后">晚上</Tooltip>},
                ]}
            />
        </Form.Item>
    </>
}

// 联系方式输入框-Input
class InputPhoneNumber extends Component {
    constructor(props) {
        super(props);
        const label = props.label || "联系方式";
        const rules = props.rules || [];
        if (props.required) rules.push({required: 'true', message: label + '为必填项'})
        this.state = {
            label,
            placeholder: props.placeholder || "请输入联系方式",
            keyword: props.keyword || "lxfs",
            colSpan: props.colSpan || 4,
            rules,
            title: props.placeholder || "请输入联系方式",
            value: null
        }
    }

    handleChange = (e) => {
        const text = e.target.value;
        const value = text.replace(/\s+/g, "");
        // const value = text.trim();
        const title = value ? (Utils.checkTelephone(value) || "联系方式不符合手机号") : this.state.placeholder;
        this.setState({value, title})
    }

    render() {
        const {placeholder, colSpan, keyword, rules, value, title} = this.state;
        return (
            <>
                <Col span={colSpan} key={keyword}>
                    <Form.Item
                        label={this.state.label}
                        name={this.state.keyword}
                        rules={rules}>
                        <Tooltip
                            trigger={['focus']}
                            title={title}
                            placement="topLeft"
                            classNames={{root: 'numeric-input'}}
                        >
                            <Input value={value} onChange={this.handleChange} placeholder={placeholder}/>
                        </Tooltip>
                    </Form.Item>
                </Col>
            </>
        )
    }
}

// 模糊搜索-Input
function InputFuzzy({onFormChange, colSpan, keyword = "search"}) {
    const onBlur = (e) => {
        if (onFormChange) onFormChange({
            [keyword]: e ? e.target.value : null
        }, e)
    }

    return (
        <Col span={colSpan || 4}>
            <Form.Item label='模糊搜索' name={keyword}>
                <Input placeholder="输入关键字" onBlur={onBlur}></Input>
            </Form.Item>
        </Col>
    )
}

// 计数-InputNumber
function InputCount(
    {
        onFormChange,
        colSpan,
        step = 5,
        label = "每日留资数",
        keywork = 'mrlzs',
        min = -Infinity,
        max = Infinity
    }) {
    const [value, setValue] = useState(0);

    const onChange = (e) => {
        if (onFormChange) onFormChange({
            [keywork]: value
        }, e)
    }

    const onInput = (val) => {
        const num = Number(val);
        if (isNaN(num)) return;// 格式异常
        setValue(num < min ? min : num > max ? max : val);
    }

    // const handleStepUp = () => {
    //     const result = Math.min(~~value + step, max);
    //     setValue(result);
    // }
    //
    // const handleStepDown = () => {
    //     const result = Math.max(~~value - step, min);
    //     setValue(result);
    // }

// .ant-input-number-group-addon:hover {
//     cursor: pointer;
//  }
    return (
        <Col span={colSpan || 8}>
            <Form.Item
                label={label}
                name={keywork}
            >
                <InputNumber
                    controls={false}
                    value={value}
                    min={min}
                    max={max}
                    step={step}
                    onChange={onChange}
                    onInput={onInput}
                    defaultValue={0}
                    // addonBefore={<span onClick={handleStepDown}>-</span>}
                    // addonAfter={<span onClick={handleStepUp}>+</span>}
                ></InputNumber>
            </Form.Item>
        </Col>
    )
}

// 节流防抖
class ButtonLock extends Component {
    constructor(props) {
        super(props);
        this.state = {
            colSpan: props.colSpan || 0,
            icon: props.icon || null,
            text: props.text || props.children || "",
            className: props.className || "",
            // htmlType: props.htmlType,
            lock: false,
            type: props.type || "",
        }
        this.props.onClick && (this.onClick = this.props.onClick);
    }

    // lock = false;
    start = 0;
    timeout = 500;// ms

    onClick = () => {
        return new Promise(resolve => {
            console.warn("异常：理应被重写");
            resolve();
        })
    };

    reset = () => {
        const t = this.timeout - (Date.now() - this.start);

        setTimeout(() => {
            this.setState({lock: false})
            this.start = 0;
        }, t > 0 ? t : 0)
    }

    onClickCallback = () => {
        if (this.state.lock) return;
        this.setState({lock: true})
        this.start = Date.now();
        const result = this.onClick();
        if (result instanceof Promise) {
            result.finally(() => {
                this.reset();
            })
        } else {
            this.reset();
        }
    }

    render() {
        const {colSpan, icon, text, className, lock, type} = this.state;
        const button = <Button
            icon={icon}
            onClick={this.onClickCallback}
            // disabled={lock}
            loading={lock}
            className={className}
            type={type}
        >
            {text}
        </Button>
        return (
            colSpan ?
                <Col span={colSpan}>
                    {button}
                </Col> : button
        )
    }
}

class ButtonQuery extends ButtonLock {
    constructor(props) {
        super(props);
        this.state.icon = <SearchOutlined/>;
        this.state.colSpan = props.colSpan || 2;
        this.state.text = props.text || "查询";
        this.state.className = props.className || "search-button";
        const {queryDataList} = props;
        queryDataList && (this.onClick = queryDataList);
    }
}

// 新增-button
function ButtonAdd(props) {
    const {setHandler, span} = props;
    return (
        <Col span={span || 2}>
            <Button
                onClick={() => setHandler('create')}
                icon={<FileAddOutlined/>}
                className="addButton"
            >
                新增
            </Button>
        </Col>
    )
}

// 导出-button
// SheetJS 中文网: https://xlsx.nodejs.cn/
// npm i xlsx -s
class ButtonExport extends ButtonLock {
    constructor(props) {
        super(props);
        this.state.icon = <DownloadOutlined/>;
        this.state.colSpan = props.colSpan || 2;
        this.state.text = props.text || "导出";
        this.state.className = props.className || "search-button";
        this.data = [];
        this.onClick = this.exportExcel;
    }

    // 导出 Excel 文件
    exportExcel = () => {
        return new Promise((resolve, reject) => {
            const {queryDataList, getDateRange} = this.props;
            const exportConfirm = this.exportConfirm;
            if (getDateRange) {
                const {start, end} = getDateRange();
                if (moment(end, defDateFormat) - moment(start, defDateFormat) > 7 * 24 * 3600 * 1000) {
                    message.warn("日期范围过长，需等待较长时间");
                    // reject();
                    // return;
                }
            }
            if (!queryDataList) {
                console.error("导出组件需要传递查询方法：queryDataList");
                reject();
                return;
            }
            const result = queryDataList(false);
            if (!(result instanceof Promise)) {
                console.error("queryDataList需要return Promise")
                reject();
                return;
            }
            result.then(list => {
                this.data = list;
                exportConfirm(list);
                resolve();
            }).catch(() => reject())
        })
    };

    // 确认导出Excel
    exportConfirm = (list) => {
        const columns = this.props.columns;
        Utils.exportAsExcel({
            list,
            filename: this.props.filename,
            columns,
            sumRow: this.props.sumRow
        })
    }
}

export {
    // 公司名称
    SelectCompanies,
    // 文本输入框
    InputText,
    periodRadio,
    // 模糊查询
    InputFuzzy,
    // 跟进状态下拉框
    SelectFollowState,
    // 意向项目
    SelectProjects,
    // 日期开始
    // startDate: "",
    // 日期结束
    // endDate: "",
    // 日期选择器
    // MyDatePicker,
    // 合并时间段
    DatePickerRange,
    // 选择日期
    ChooseDatePickerRange,
    // 平台
    SelectPlatform,
    // 计划下拉
    JhSelect,
    // 拍摄项目
    // SelectShootProjects,
    // 拍摄状态
    SelectShootStates,
    // 人员列表
    SelectPerson,
    // 客服/销售-wx
    SelectPersonWx,
    // 微信客服
    SelectPersonWx2,
    // 导购
    SelectPersonZw,
    // 客服-dy
    SelectPersonDy,
    // 创建者
    SelectCreator,
    // 联系来源
    SelectChannel,
    // 核对与否
    SelectCheck,
    // 职务
    SelectPositions,
    // 账号
    SelectAccount,
    SelectJhAccount,
    // 计数器
    InputCount,
    // 联系方式
    InputPhoneNumber,
    // 是否有效
    SelectState,
    SelectState2,
    // 职位 2、6
    ZwSelect,
    // 节流防抖按钮
    ButtonLock,
    // 查询btn
    ButtonQuery,
    // 新增
    ButtonAdd,
    // 导出
    ButtonExport,
}